package api

import (
	"net/http"
	"gitee.com/DengAnbang/Computation/src/code"
	"gitee.com/DengAnbang/goutils/update"
	"gitee.com/DengAnbang/goutils/fileUtil"
	"os"
	"html/template"
	"gitee.com/DengAnbang/Computation/src/bean"
	"fmt"
	"net/url"
)

var Apis = make(map[string]AppHandleFuncErr, 10)

func test(w http.ResponseWriter, r *http.Request) error {
	t, err := template.ParseFiles(code.ViewRootPath + "index.html")
	if err != nil {
		//http.Error(w, err.Error(), http.StatusInternalServerError)
		return err
	}
	t.Execute(w, nil)
	return nil
}
func Run(port string, mux *http.ServeMux) {

	//Apis["/"] = test
	Apis["/public/log/switch"] = LogSwitch
	Apis["/public/file/upload"] = FileUpload
	Apis["/public/sys/restart"] = SysRestart
	Apis["/public/database/backups"] = DatabaseBackups
	Apis["/public/database/restore"] = DatabaseRestore
	Apis["/public/database/clearRedundantData"] = ClearRedundantData
	Apis["/public/authentication/pcLic"] = AuthenticationLicPC
	//用户相关
	Apis["/pc/user/register"] = UserRegisterHttp
	Apis["/pc/user/login"] = UserLoginHttp
	//树相关
	Apis["/pc/tree/create"] = CreateTreeHttp
	Apis["/pc/tree/addNode"] = AddTreeNodeHttp
	Apis["/pc/tree/deleteTreeNode"] = DeleteTreeNodeHttp
	Apis["/pc/tree/selectTreeNodeList"] = SelectTreeNodeListHttp
	Apis["/pc/tree/renameTreeNode"] = RenameTreeNodeHttp
	Apis["/pc/tree/getMyTreeNode"] = GetMyTreeNodeHttp
	Apis["/pc/tree/getUserTreeList"] = GetUserTreeListHttp
	//模板相关
	Apis["/pc/template/add"] = AddTemplateNodeHttp
	Apis["/pc/template/amend"] = AmendTemplateNodeHttp
	Apis["/pc/template/select"] = SelectTemplateListHttp
	Apis["/pc/template/deleteByID"] = DeleteTemplateByIDHttp
	Apis["/pc/template/deleteByNode"] = DeleteTemplateByNodeHttp
	Apis["/pc/template/importExcelTree"] = ImportExcelTreeHttp
	Apis["/pc/template/exportExcelTree"] = ExportExcelTreeHttp
	//模型相关
	Apis["/pc/model/file/upload"] = B3DFileUpload
	Apis["/pc/model/modelBean"] = GetModelBeanHttp
	Apis["/pc/model/modelBeanList"] = GetModelBeanListHttp
	Apis["/pc/model/selectModelTree"] = SelectModelTreeHttp
	Apis["/pc/model/selectModelNodeAddition"] = SelectModelNodeAdditionHttp

	mux.Handle(code.RootName, http.StripPrefix(code.RootName, FileHandler{}))
	mux.Handle("/log/", http.StripPrefix("/log/", http.FileServer(http.Dir(code.LogRootPath))))
	for k, v := range Apis {
		mux.HandleFunc(k, AppHandleFunc(v))
	}
	update.UpgradeService(":"+port, mux)
}

type FileHandler struct{}

func (f FileHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	values, _ := url.PathUnescape(r.URL.String())
	fileName := code.RootPath + values
	if fileUtil.PathExists(fileName) {
		f, _ := os.Stat(fileName)
		if !f.IsDir() {
			http.ServeFile(w, r, fileName)
			return
		}
	}
	http.NotFound(w, r)
}

type AppHandleFuncErr func(w http.ResponseWriter, r *http.Request) (error)

func AppHandleFunc(appHandle AppHandleFuncErr) func(http.ResponseWriter, *http.Request) {
	return func(w http.ResponseWriter, r *http.Request) {
		defer func() {
			i := recover()
			if resultData, ok := i.(*bean.ResultData); ok {
				resultData.WriterResponse(w)
			} else if err, ok := i.(error); ok {
				data := bean.NewErrorMessage("服务器内部错误")
				data.DebugMessage = fmt.Sprintf("%v", err)
				data.WriterResponse(w)
			}
		}()
		err := appHandle(w, r)
		if resultData, ok := err.(*bean.ResultData); ok {
			resultData.WriterResponse(w)
		} else if err != nil {
			data := bean.NewErrorMessage("服务器内部错误")
			data.DebugMessage = fmt.Sprintf("%v", err)
			data.WriterResponse(w)
		}
	}
}
